package com.cskaoyan.controller;

import com.cskaoyan.bean.*;
import com.cskaoyan.bean.param.BaseParam;
import com.cskaoyan.exception.ValidationException;
import com.cskaoyan.service.GoodsService;
import com.cskaoyan.util.ValidationUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * @author Kongwo
 * @description
 * @since 2022/05/05 19:44
 */

@RestController
@RequestMapping("admin/goods")
public class GoodsController {

    @Autowired
    GoodsService goodsService;

    @GetMapping("list")
    public BaseRespVo goodsList(String goodsId, String goodsSn, String name, BaseParam param) {

        GoodsData goodsData = goodsService.getGoodsForPage(goodsId, goodsSn, name, param);
        return BaseRespVo.ok(goodsData);
    }

    @PostMapping("create")
    public BaseRespVo addGoods(@Validated @RequestBody GoodsInfoBO goodsInfoBO, BindingResult bindingResult) throws ValidationException {

        ValidationUtil.valid(bindingResult);
        if (goodsService.checkGoodsName(goodsInfoBO.getGoods().getName(), goodsInfoBO.getGoods().getId())) {
            return BaseRespVo.invalidParameter("商品名称重复！");
        }
        goodsService.addNewGoods(goodsInfoBO);
        return BaseRespVo.ok(null);
    }


    @PostMapping("update")
    public BaseRespVo updateGoods(@Validated @RequestBody GoodsInfoBO goodsInfoBO, BindingResult bindingResult) throws ValidationException {

        ValidationUtil.valid(bindingResult);
        if (goodsService.checkGoodsName(goodsInfoBO.getGoods().getName(), goodsInfoBO.getGoods().getId())) {
            return BaseRespVo.invalidParameter("商品名称重复！");
        }
        goodsService.updateGoods(goodsInfoBO);
        return BaseRespVo.ok(null);
    }



    @PostMapping("delete")
    public BaseRespVo deleteGoods(@RequestBody MarketGoods marketGoods) {

        goodsService.deleteGoods(marketGoods);
        return BaseRespVo.ok(null);
    }

    @GetMapping("detail")
    public BaseRespVo getGoodsDetail(Integer id) {

        GoodsInfoBO goodsInfo = goodsService.getGoodsDetail(id);
        return BaseRespVo.ok(goodsInfo);
    }

    @GetMapping("catAndBrand")
    public BaseRespVo catAndBrand() {

        CatAndBrandVO catAndBrandVO = goodsService.getCatAndBrandList();
        return BaseRespVo.ok(catAndBrandVO);
    }
}
